<?php

namespace admin\models\forms;

use admin\models\Adminer;
use yii\base\Model;

/**
 * LoginForm is the model behind the login form.
 *
 * @property-read Adminer|null $user This property is read-only.
 *
 */
class LoginForm extends Model
{
    public $mobile;
    public $password;
    public $code;
    public $rememberMe = false;

    private $_user = false;

    public function attributeLabels()
    {
        return [
            'mobile' => "手机号",
            'password' => "密码",
            'code' => "验证码",
            'rememberMe' => '记住我30天',
        ];
    }

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            [['mobile', 'password', 'code'], 'trim'],
            [['mobile', 'password', 'code'], 'required'],
            ['password', 'validatePassword'],
            ['code', 'captcha'],
            ['rememberMe', 'boolean'],
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if (!$user) {
                $this->addError('mobile', '未找到管理员');
            } else {
                if ($user->status !== Adminer::STATUS_ACTIVE) {
                    $this->addError('mobile', '账号未启用');
                }
                $password = md5(md5($this->password));
                if (!$user->validatePassword($password)) {
                    $this->addError($attribute, '账户或密码错误');
                }
            }
        }
    }

    /**
     * Logs in a user using the provided username and password.
     * @return bool whether the user is logged in successfully
     */
    public function login()
    {
        if ($this->validate()) {
            return \Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
        }
        return false;
    }

    /**
     * Finds user by [[username]]
     *
     * @return Adminer|null
     */
    public function getUser()
    {
        if ($this->_user === false) {
            $this->_user = Adminer::findByMobile($this->mobile);
        }

        return $this->_user;
    }
}